<template>
  <div class="home">
    <img
      ref="img"
      :src="configStore.imgUrl"
      class="img no-drag"
      draggable="false"
      alt="壁纸预览图"
      @click="load"
    />
    <div class="oper">
      <div class="btn no-drag" @click="setWallpaper">设为壁纸</div>
      <div class="copyright">
        <div>版权所有</div>
        <div class="down no-drag" @click="downloadImage">下载壁纸</div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElLoading } from 'element-plus'
import { http } from '@renderer/plugins/axios'
import { useConfigStore } from '@renderer/store/useConfigStore'
import useWallpaper from '@renderer/hooks/useWallpaper'
import { ref, onMounted } from 'vue'

const configStore = useConfigStore()
const { setWallpaper, downloadImage } = useWallpaper()

const img = ref<HTMLImageElement>()

async function getImgUrl() {
  const imgUrl = await http.get<string, string>('/random-img')
  return imgUrl
}

async function load() {
  const loading = ElLoading.service({ fullscreen: true, background: 'rgba(255, 255, 255, 0.2)' })
  const imgUrl = await getImgUrl()

  // 存储到中央仓库中
  configStore.imgUrl = imgUrl

  // 调用一个 url,每次返回一个随机的图片 url 地址
  img.value!.src = imgUrl

  img.value!.addEventListener('load', () => {
    loading.close()
  })

  img.value!.addEventListener('error', () => {
    loading.close()
  })
}

onMounted(() => {
  if (!configStore.imgUrl) {
    load()
  }
})
</script>

<style lang="less" scoped>
.home {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  height: calc(100vh - 38px);

  .img {
    display: block;
    height: 216px;
    cursor: pointer;
  }

  .oper {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin: 15px 15px 0;

    .btn {
      padding: 8px;
      text-align: center;
      border-radius: 8px;
      background: #c7ced0;
      cursor: pointer;

      &:hover {
        background: #dee2e3;
      }
    }

    .copyright {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 13px;
      opacity: 0.6;

      .down {
        cursor: pointer;

        &:hover {
          font-weight: bold;
        }
      }
    }
  }
}
</style>
